<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>只能输入数字</title>
  <style>
    input {
      border: none;
      outline: none;
      border: 1px solid #ccc;
      height: 40px;
      width: 150px;
      display: block;
      margin: 0 auto;
      border-radius: 5px;
      padding: 0 1em;
    }
  </style>
</head>

<body>
  <input type="text" placeholder="请输入商品价格" id="priceInput" />

  <script>
    var numberArr = ['Backspace']
    for (let index = 0; index < 10; index++) {
      numberArr.push(index.toString())
    }
    var priceInput = document.querySelector('#priceInput')
    priceInput.addEventListener('keydown', function (e) {
      console.log(e.key);
      if (!numberArr.includes(e.key)) {
        //阻止输入框的默认行为
        e.preventDefault()
      }
    })
    // 上面的文本框只能输入数字
  </script>
</body>

</html>